#ifndef _LOG_HPP__
#define _LOG_HPP__

#include <iostream>
#include <string>
#include "Mutex.hpp"
#include <filesystem> //C++17
#include <fstream>
#include <sstream>
#include <memory>
#include <unistd.h>
#include<time.h>
#include<cstdio>


namespace MyLog
{
    using namespace MyMutex;
    const std::string gsep = "\r\n";

    // 日志刷新策略
    class LogStrategy
    {
    public:
        ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 显示器打印
    class ConsoleLogStrategy : public LogStrategy
    {

    public:
        ConsoleLogStrategy() {}

        void SyncLog(const std::string &message) override
        {
            LockGuard lockg(_mutex);
            std::cout << message << "\r\n";
        }

        ~ConsoleLogStrategy() {}

    private:
        Mutex _mutex;
    };

    // 写入文件
    const std::string defaultpath = "./log/";
    const std::string defaultfile = "my.log";
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &file = defaultfile)
            : _path(path), _file(file)
        {
            LockGuard lockg(_mutex);
            if (std::filesystem::exists(_path))
            {
            }
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << "\n";
            }
        }

        void SyncLog(const std::string &message) override
        {
            LockGuard lockg(_mutex);
            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            std::ofstream out(filename, std::ios::app);
            if (!out.is_open())
            {
                return;
            }

            out << message << gsep;
            out.close();
        }

        ~FileLogStrategy()
        {
        }

    private:
        std::string _path; // 文件路径
        std::string _file; // 日志文件本体
        Mutex _mutex;
    };

    // 日志等级
    enum class Loglevel
    {
        DEBUG,
        INFO,
        WARN,
        ERROR,
        FATAL
    };

    std::string Leveltostr(Loglevel level)
    {
        switch (level)
        {
        case Loglevel::DEBUG:
            return "DEBUG";
        case Loglevel::INFO:
            return "INFO";
        case Loglevel::WARN:
            return "WARN";
        case Loglevel::ERROR:
            return "ERROR";
        case Loglevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    std::string GetTimeStamp()
    {
        time_t cur = time(nullptr);
        struct tm cur_tm;
        localtime_r(&cur,&cur_tm);
        char timebuffer[128];

        snprintf(timebuffer,sizeof(timebuffer),"%02d-%02d-%02d %02d:%02d:%02d",
                cur_tm.tm_year+1900,
                cur_tm.tm_mon+1,
                cur_tm.tm_mday,
                cur_tm.tm_hour,
                cur_tm.tm_min,
                cur_tm.tm_sec
                );

        return std::string(timebuffer);
    }

    // 形成日志
    class Logger
    {
    public:
        Logger()
        {
            EnableConsoleLogStrategy();
        }

        void EnableFileLogStrategy()
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }

        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }

        // 形成一条日志
        class LogMessage
        {
        public:
            LogMessage(Loglevel &level, std::string &src_name, int line_number, Logger &logger)
                : _cur_time(GetTimeStamp()), _level(level), _pid(getpid()), _src_name(src_name), _line_number(line_number), _logger(logger)
            {
                // 合并日志左半部分
                std::stringstream ss;
                ss << "[" << _cur_time << "]"
                   << "[" << Leveltostr(_level) << "]"
                   << "[" << _pid << "]"
                   << "[" << _src_name << "]"
                   << "[" << _line_number << "]"
                   << "- ";
                _loginfo = ss.str();
            }

            // 日志右半部分
            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if (_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _cur_time;
            Loglevel _level;
            pid_t _pid;
            std::string _src_name;
            int _line_number;
            std::string _loginfo; // 合并后的完整信息
            Logger &_logger;
        };

        LogMessage operator()(Loglevel level, std::string name, int line)
        {
            return LogMessage(level, name, line, *this);
        }

        ~Logger()
        {
        }

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    //全局日志对象
    Logger log;
    #define LOG(level) log(level,__FILE__,__LINE__)
    #define Enable_File_Log_Strategy() log.EnableFileLogStrategy()
    #define Enable_Console_Log_Strategy() log.EnableConsoleLogStrategy()
} // namespace MyLog

#endif
